package com.ssl.spring.security.auth;

import com.ssl.spring.security.auth.entity.AuthUser;
import com.ssl.spring.security.auth.entity.SecurityUserDetail;
import com.ssl.spring.security.entity.User;
import com.ssl.spring.security.service.IPermissionService;
import com.ssl.spring.security.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 描述：从数据库获取用户信息，交给 SpringSecurity 去做身份认证和授权
 *
 * @author shi_senlin
 * @create 2021/04/28 21:21
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 根据用户名查找用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);
        if (null == user) {
            throw new UsernameNotFoundException("根据用户名[".concat(username).concat("]未找到用户。"));
        }
        AuthUser authUser = new AuthUser();
        // 将user对象的属性 copy 到 authUser 上
        BeanUtils.copyProperties(user, authUser);
        //根据用户查询用户权限列表
        List<String> permissionValueList = permissionService.getPermissionValueByUserId(user.getId());
        SecurityUserDetail userDetail = new SecurityUserDetail();
        userDetail.setAuthUser(authUser);
        userDetail.setPermissionValueList(permissionValueList);
        return userDetail;
    }
}
